<?php
function data_ptbr($data){
    $ano = substr($data, 0, 4);
    $mes = substr($data, 5, 2);
    $dia = substr($data, 8, 2);
    $hora = substr($data, 10);
    if($data){
        return $dia."/".$mes."/".$ano.$hora;
    }else{
        return null;
    }
}

function data_inter($data){
    $dia = substr($data, 0, 2);
    $mes = substr($data, 3, 2);
    $ano = substr($data, 6, 4);
    if($data){
        return "$ano-$mes-$dia";
    }else{
        return null;
    }
}

function soma_data($n, $data = NULL) {
    if($data){
        $data = data_inter($data);
        $ano = substr($data, 0, 4);
        $mes = substr($data, 5, 2);
        $dia = substr($data, 8);
    }else{
        $dia = date("d");
        $mes = date("m");
        $ano = date("Y");
    }

    $tmp = $ano;
    if($tmp > 2012){
            while($tmp > 2012) {
                    $tmp -=4;
            }
    }elseif($tmp < 2012){
            while($tmp < 2012) {
                    $tmp +=4;
            }
    }
    if($tmp == 2012){
            $bissexto = 1;
    }else {
            $bissexto = 0;
    }

    for($x = 0; $x < $n; $x++) {
            $dia++;
            if($mes == 2){
                    if($bissexto == 1){
                            if($dia == 30){ $dia = 1; $mes = 3; }
                    }else {
                            if($dia == 29){ $dia = 1; $mes = "3"; }
                    }
            }elseif($mes == "04" || $mes == "06" || $mes == "09" || $mes == "11") {
                    if($dia == 31){ $dia = 1; $mes++; }
            }else {
                    if($dia == 32){ $dia = 1; $mes++; }
                    if($mes == 13){ $mes = 1; $ano++; }
            }
    }

    if($dia < 10 && strlen($dia) < 2){
            $dia = "0".$dia;
    }

    if($mes < 10 && strlen($mes) < 2){
            $mes = "0".$mes;
    }
    return $ano."-".$mes."-".$dia;
}

function paginas($tpag, $url, $pag = 1){
    $qnt = 500;
    $p = $tpag / $qnt;
    
    $t = explode('.', $p);
    if($t[0] > 0){
        if($t[1] > 0 && $t[1] != ''){
            $p = $t[0] + 1;
        }else{
            $p = $t[0];
        }

        echo "
        <br>
        <div id='paginas'>";
        for($i = 1; $i <= $p; $i++){
            if($pag == $i){
                echo "
                <div class='p1'>$i</div>";
            }else{
                echo "
                <a href='$url&p=$i'>
                    <div class='p'>$i</div>
                </a>";
            }
        }
        echo "
            <div style='clear: both'></div>
        </div>
        <br>";
    }
}

function add_0_inicio($str, $tam){
    $z = "";
    for($i = 0; $i < ($tam - strlen($str)); $i++){
        $z .= "0";
    }
    
    return $z.$str;
}